package JavaEE_notes.common_API;

import com.wl.week_01.Student;

import java.util.*;
import java.util.stream.Stream;

/**
 * 对 Stream API 的练习
 * @author TaiZai
 * @data 2024/9/21 16:33
 */
public class api_Stream {
    public static void main(String[] args) {
        /*
          如何创建 List、Set、Map、数组的Stream流
         */
        List<Integer> numbers = new ArrayList<>();
        Collections.addAll(numbers, 1, 2, 3, 4, 5);
        Stream<Integer> stream1 = numbers.stream();

        Set<String> names = new HashSet<>();
        Collections.addAll(names, "Alice", "Bob", "Charlie");
        Stream<String> stream2 = names.stream();

        Map<String, Integer> map = new HashMap<>();
        map.put("Alice", 18);
        map.put("Bob", 20);
        map.put("Charlie", 19);
        Stream<Map.Entry<String, Integer>> stream3 = map.entrySet().stream();

        Integer[] numbersArray = {1, 2, 3, 4, 5};
        Stream<Integer> stream4 = Arrays.stream(numbersArray);

        /*
          如何使用 Stream API 进行元素的操作
         */
        List<Integer> scores = new ArrayList<>();
        Collections.addAll(scores, 85, 92, 78, 88, 95);
        // 找出成绩小于90的并输出
        scores.stream()
                .filter(sc -> sc < 90)
                .forEach(s -> System.out.printf("%d ", s));
        System.out.println();

        // 将所有的成绩减去10
        scores.stream()
                .map(sc -> sc - 10)
                .sorted(Comparator.comparingInt(Integer::intValue).reversed())
                .forEach(sc -> System.out.printf("%d ", sc));
        System.out.println();

        List<Student> students = new ArrayList<>();
        Student s1 = new Student("蜘蛛精", 26, 172.5);
        Student s2 = new Student("蜘蛛精", 26, 172.5);
        Student s3 = new Student("紫霞", 23, 167.6);
        Student s4 = new Student("白晶晶", 25, 169.0);
        Student s5 = new Student("牛魔王", 35, 183.3);
        Student s6 = new Student("牛夫人", 34, 168.5);
        Collections.addAll(students, s1, s2, s3, s4, s5, s6);
        // 找出年龄再20-30之间的人物并按照年龄进行降序输出
        students.stream()
                .filter(st -> st.getAge() >= 20 && st.getAge() <= 30)
                .sorted(Comparator.comparingInt(Student::getAge).reversed())
                //.forEach(st -> System.out.println(st));
                .forEach(System.out::println);

        // 找出身高超过168的学生叫什么名字，要求去除重复的名字，再输出。
        students.stream().filter(s -> s.getHeight() > 168).map(Student::getName)
                .distinct().forEach(System.out::println);
    }
}
